package com.zfx.service.impl;

import com.github.pagehelper.PageHelper;
import com.zfx.mapper.IAddressMapper;
import com.zfx.mapper.IUserMapper;
import com.zfx.pojo.Address;
import com.zfx.pojo.User;
import com.zfx.service.IAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @description:
 * @author: zfx
 */
@Service
public class AddressServiceImpl implements IAddressService {

    @Autowired
    private IAddressMapper addressMapper;

    @Autowired
    private IUserMapper userMapper;


    @Transactional(readOnly = true)
    @Override
    public List<Address> findByAddress(Address address, int page, int size) {
        PageHelper.startPage(page, size);
        return addressMapper.findByAddress(address);
    }

    @Transactional(readOnly = true)
    @Override
    public Address findByUserIdAndHaoyouId(Address address) {
        return addressMapper.selectOne(address);
    }

    @Transactional(readOnly = true)
    @Override
    public int countAll(Address address) {
        return addressMapper.countByAddress(address);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int update(Address address) {
        return addressMapper.updateByPrimaryKeySelective(address);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(Address address) {
        if (address.getHaoyouId().equals(address.getUserId())) {
            throw new RuntimeException("用户相同");
        }
        User user = userMapper.selectByPrimaryKey(address.getUserId());
        User friend = userMapper.selectByPrimaryKey(address.getHaoyouId());
        if( user != null && friend != null) {
            Address address1 = new Address();
            address1.setUserId(address.getUserId());
            address1.setHaoyouId(address.getHaoyouId());
            address1.setPhone(friend.getPhone());
            address1.setNickName(friend.getUsername());
            addressMapper.insert(address1);
            Address address2 = new Address();
            address2.setUserId(address.getHaoyouId());
            address2.setHaoyouId(address.getUserId());
            address2.setPhone(user.getPhone());
            address2.setNickName(user.getUsername());
            addressMapper.insert(address2);
        } else {
            throw new RuntimeException("用户/好友不存在");
        }
    }

    @Override
    public int delete(Address address) {
        return addressMapper.delete(address);
    }

    @Transactional(readOnly = true)
    @Override
    public boolean existsWithUserIdAndHaoyouId(Address address) {
        return addressMapper.existsWithUserIdAndHaoyouId(address) != null ? true : false;
    }
}
